'    Copyright 2008 Jan Molnar <jan.molnar@abds.de>
'
'    This file is part of JCQ.

'    JCQ is free software: you can redistribute it and/or modify
'    it under the terms of the GNU General Public License as published by
'    the Free Software Foundation, either version 2 of the License, or
'    (at your option) any later version.

'    JCQ is distributed in the hope that it will be useful,
'    but WITHOUT ANY WARRANTY; without even the implied warranty of
'    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'    GNU General Public License for more details.

'    You should have received a copy of the GNU General Public License
'    along with JCQ. If not, see <http://www.gnu.org/licenses/>.

Public Class AvatarSelectorViewModel
    Private _ImageSelector As ImageSelectorViewModel
    Private _Identity As IdentityManager.IIdentity

    Public Sub New(ByVal identity As IdentityManager.IIdentity)
        _ImageSelector = New ImageSelectorViewModel(ApplicationService.Current.DataStorageDirectory)
        _Identity = identity
    End Sub

    Public ReadOnly Property ImageSelector() As ImageSelectorViewModel
        Get
            Return _ImageSelector
        End Get
    End Property

    Public Sub SelectImageFile()
        Dim imageFile As System.IO.FileInfo

        Dim sourceBitmap As BitmapImage
        Dim visual As Image
        Dim targetBitmap As RenderTargetBitmap
        Dim encoder As JpegBitmapEncoder

        imageFile = New System.IO.FileInfo(ImageSelector.SelectedImageFile)

        If imageFile.Exists Then
            sourceBitmap = New BitmapImage(New Uri(imageFile.FullName))

            visual = New Image
            visual.Source = sourceBitmap
            visual.Arrange(New Rect(0, 0, 48, 48))

            targetBitmap = New RenderTargetBitmap(48, 48, 96, 96, PixelFormats.Default)

            targetBitmap.Render(visual)

            encoder = New JpegBitmapEncoder
            encoder.Frames.Add(BitmapFrame.Create(targetBitmap))

            Dim newfile As String = System.IO.Path.Combine(ApplicationService.Current.DataStorageDirectory.FullName, String.Format("{0}.default.jpg", _Identity.Identifier))

            Using fs = New System.IO.FileStream(newfile, IO.FileMode.Create, IO.FileAccess.Write)
                encoder.Save(fs)
            End Using

            _Identity.ImageUrl = newfile
        Else
            _Identity.ImageUrl = Nothing
        End If
    End Sub
End Class